//
//  HJScanController.m
//  KaiChat
//
//  Created by lx on 2024/4/7.
//

#import "HJScanController.h"
#import "HJScanView.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/PHPhotoLibrary.h>
#import "HJButton.h"
#import "HJFlutterManager.h"
#import "HJFlutterMethod.h"
#import "HJUserInfoController.h"
#import "HJNavigationController.h"
#import "HJAlertController.h"
#import "HJIM.h"
#import "HJNetworkReachabilityManager.h"
#import "HJFlutterController.h"

@interface HJScanController ()<HJScanViewDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (weak, nonatomic) HJScanView *scanView;
@property (strong, nonatomic) UIActivityIndicatorView *activitydicator;
@property (strong, nonatomic) AVCaptureDevice *device;
@property (assign, nonatomic) BOOL lightOn;
@property (nonatomic, weak) HJButton *flashlightButton;


@end


@implementation HJScanController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addSubView];
}

- (void)showInController:(UIViewController *)controller {
    HJNavigationController *navigationController = [[HJNavigationController alloc] initWithRootViewController:self];
    [controller presentViewController:navigationController animated:YES completion:nil];
}

- (void)addSubView {
    
    self.view.backgroundColor = UIColor.blackColor;
    self.navigationBar.alpha = 0;
    [self.navigationBar.backBarButton whiteColor];
    self.navigationBar.title = @"Scan QR Code";
    self.navigationBar.titleTextColor = UIColor.whiteColor;
    
    self.navigationBar.rightBarButton = [HJBarButton barButtonWithImage:[UIImage imageNamed:@"icon_album"] target:self action:@selector(didClickAlbumButton)];
   
    AVAuthorizationStatus authStatus =  [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
     
        dispatch_after_main_queue(0.5, ^{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Tip" message:@"Don’t have permission to use your camera to scan QR codes? Go to enable it?" preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            }]];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"Open" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
            }]];
            
            [self presentViewController:alert animated:YES completion:nil];
        });
     
        return;
    }
    
    HJScanView *scanView = [[HJScanView alloc] initWithFrame:self.view.bounds];
    scanView.delegate = self;
    _scanView = scanView;
    [self.view addSubview:scanView];
    
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    
    HJButton *qrcodeButton = [HJButton buttonWithSuperView:scanView font:UIFontMediumMake(14) color:UIColor.whiteColor title:@"My QR Code"];
    qrcodeButton.addCornerRadius(10);
    [qrcodeButton addTarget:self action:@selector(didClickQrcodeButton) forControlEvents:UIControlEventTouchUpInside];
    [qrcodeButton setImage:[UIImage imageNamed:@"scan_qrcode_icon"] forState:UIControlStateNormal];
    qrcodeButton.backgroundColor = UIColorMake(0x7f7f7f);
    qrcodeButton.imagePosition = QMUIButtonImagePositionLeft;
    qrcodeButton.spacingBetweenImageAndTitle = 5;
    [qrcodeButton sizeToFit];
    [qrcodeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(140);
        make.height.offset(40);
        make.centerX.offset(0);
        make.width.offset(qrcodeButton.tj_width + 20);
    }];
    
    if ([_device hasTorch]) {
        
        HJButton *flashlightButton = [HJButton buttonWithSuperView:scanView font:UIFontMake(10) color:UIColor.whiteColor title:@""];
        flashlightButton.addCornerRadius(20);
        [flashlightButton addTarget:self action:@selector(didClickFlashlightButton:) forControlEvents:UIControlEventTouchUpInside];
        [flashlightButton setImage:[UIImage imageNamed:@"flashlight_icon"] forState:UIControlStateSelected];
        [flashlightButton setImage:[UIImage imageNamed:@"flash_icon"] forState:UIControlStateNormal];
        flashlightButton.backgroundColor = UIColorMake(0x7f7f7f);
        [flashlightButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.offset(40);
            make.top.equalTo(qrcodeButton.mas_bottom).offset(15);
            make.centerX.offset(0);
        }];
     
        _flashlightButton = flashlightButton;
    }
    
    UILabel *tipLabel = [UILabel lableWithSuperView:scanView font:UIFontMake(12) color:UIColor.whiteColor title:@"Supports scanning QR codes to add friends, make wallet transfers, log in to WalletConnect." textAlignment:NSTextAlignmentCenter];
    tipLabel.numberOfLines = 0;
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.inset(TabbarSafeBottomMargin + 40);
        make.left.right.inset(leftRightMargin);
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *scannedResult = @"";
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    if (!image) return;
    
    CIDetector*detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy : CIDetectorAccuracyHigh }];
    NSArray *features = [detector featuresInImage:[CIImage imageWithCGImage:image.CGImage]];
    if([features count] > 0){
        CIQRCodeFeature *feature = [features objectAtIndex:0];
        scannedResult = feature.messageString;
        [self handleScanResultWithResultString:scannedResult];
    } else {
        [HJAlertController alertInController:self title:nil message:@"No results found" left:nil right:^(HJAlertAction * _Nonnull action) {
            action.title = @"OK";
            action.titleColor = UIColor.tj_mainColor;
            [action setHandler:^{
                [self.scanView startRunning];
            }];
        }];
    }
}

- (void)didClickAlbumButton {
    
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {}];
    
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Tip" message:@"I don’t have permission to access the photo album. Do you want to open it?" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }]];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"Open" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
        }]];
        
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;
    
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}


- (void)didClickQrcodeButton {
    [self.navigationController pushViewControllerWithName:@"HJQrCodeController"];
}

- (void)handleScanResultWithResultString:(NSString *)resultString {
    
    TJLog(@"handleScanResultWithResultString = %@", resultString);
    
    if (self.complete) {
        self.complete(resultString);
        return;
    }
    
    if ([resultString hasPrefix:@"wc:"]) {
        [HJFlutterManager.sharedManager invokeMethod:HJFlutterMethod.scanResult arguments:resultString result:^(id  _Nullable result) {
            NSLog(@"result = %@", result);
        }];
        return;
    }
    
    NSDictionary *data = [resultString mj_JSONObject];
    if (!isEmptyString(data[@"UID"])) {
        
        if (!HJNetworkReachabilityManager.shareManager.reachable) {
            [HJHUD showErrorMessage:@"Network error"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.scanView startRunning];
            });
            return;
        }
         
        
        [HJHUD showLoadingInView:self.view];
        [HJIM.shareIM.userManager searchFridendWithKeyword:data[@"UID"] complete:^(HJChatUserModel * _Nullable model) {
           
            if (model) {
                [self dismissViewControllerAnimated:YES completion:^{
                    HJUserInfoController *userInfoController = [[HJUserInfoController alloc] init];
                    userInfoController.userId = model.userId;
                    [[HJTools currentNavController] pushViewController:userInfoController];
                }];
            } else {
                [HJAlertController alertInController:self title:nil message:@"The recipient account does not exist" left:nil right:^(HJAlertAction * _Nonnull action) {
                    action.title = @"OK";
                    action.titleColor = UIColor.tj_mainColor;
                    [action setHandler:^{
                        [self.scanView startRunning];
                    }];
                }];
            }
        }];
        return;
    }
    
    if ([HJTools isURL:resultString]) {
        HJFlutterController *flutterController = [[HJFlutterController alloc] initWithName:HJFlutterPageBrowser];
        flutterController.arguments = @{
            @"url": resultString,
        };
        [[HJTools currentNavController] pushViewController:flutterController];
        return;
    }
  
    [HJAlertController alertInController:self title:nil message:@"No results found" left:nil right:^(HJAlertAction * _Nonnull action) {
        action.title = @"OK";
        action.titleColor = UIColor.tj_mainColor;
        [action setHandler:^{
            [self.scanView startRunning];
        }];
    }];
}
 
- (void)didClickFlashlightButton:(HJButton *)button {
    
    if (![_device hasTorch]) {
        [HJHUD showMessage:@"手电筒坏了"];
        return;
    }
    
    _lightOn = !_lightOn;
    //修改之前一定要锁上
    [_device lockForConfiguration:nil];
    if (_lightOn) {
        [_device setTorchMode:AVCaptureTorchModeOn];
    } else {
        [_device setTorchMode: AVCaptureTorchModeOff];
    }
    
    [_device unlockForConfiguration];
    if (_lightOn) {
        self.flashlightButton.selected = YES;
        self.flashlightButton.backgroundColor = UIColorMake(0xf9f7fe);
    } else {
        self.flashlightButton.selected = NO;
        self.flashlightButton.backgroundColor = UIColorMake(0x7f7f7f);
    }
    
}

- (void)dismissController {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)scanView:(HJScanView *)scanView resultString:(NSString *)resultString {
    self.activitydicator.hidden = NO;
    [self.activitydicator startAnimating];
    [self playSound];
    
    [self handleScanResultWithResultString:resultString];
    
}

- (void)playSound {
    NSString *soundIDName = @"qrcode_completed.mp3";
    NSString *urlString = [NSString stringWithFormat:@"%@",[[NSBundle mainBundle] pathForResource:soundIDName ofType:nil]];
    NSURL *url = [NSURL URLWithString:urlString];
    static SystemSoundID soundID = 10000;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)url, &soundID);
    AudioServicesPlaySystemSound(soundID);
}


- (UIActivityIndicatorView *)activitydicator {
    if (!_activitydicator) {
        _activitydicator = [[UIActivityIndicatorView alloc] init];
        if (KScreenHeight < 667) {
            _activitydicator.center = CGPointMake(self.view.center.x, self.view.center.y - 32);
        } else {
            _activitydicator.center = self.view.center;
        }
        [_activitydicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
        _activitydicator.transform = CGAffineTransformMakeScale(1.4, 1.6);
        _activitydicator.hidden = YES;
    }
    return _activitydicator;
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [_scanView startRunning];
}

- (void)viewWillDisappear:(BOOL)animated {
   [super viewWillDisappear:animated];
   
   [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [_scanView stopRunning];
    [_scanView removeAnimation];
    [self.activitydicator stopAnimating];
}


- (UIModalPresentationStyle)modalPresentationStyle {
    return UIModalPresentationFullScreen;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
 

@end
